// API基础URL
const BASE_URL = 'https://autotask.top';
// const BASE_URL = 'http://127.0.0.1:8000';
// API调用封装
const API = {
    // 基础请求函数
    async request(url, options = {}) {
        const token = localStorage.getItem('access_token');
        if (!token) {
            throw new Error('未登录或登录已过期');
        }
        
        const defaultOptions = {
            headers: {
                'Authorization': token,
                'Content-Type': 'application/json'
            }
        };

        // 正确合并选项，确保headers也被正确合并
        const mergedOptions = {
            ...defaultOptions,
            ...options,
            headers: {
                ...defaultOptions.headers,
                ...(options.headers || {})
            }
        };
        
        const response = await fetch(`${BASE_URL}${url}`, mergedOptions);
        const result = await response.json();
        
        // 处理业务错误
        if (result.code !== 200) {
            const error = new Error(result.msg || '请求失败');
            error.code = result.code;
            error.details = result.details;
            throw error;
        }
        
        return result.data;
    },
    
    // 用户登录
    async login(username, password) {
        try {
            const response = await fetch(`${BASE_URL}/api/auth/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            });
            
            const result = await response.json();
            console.log('登录响应:', result);  // 添加日志
            
            if (result.code === 200 && result.data && result.data.access_token) {
                localStorage.setItem('access_token', result.data.access_token);
                return result.data;
            }
            
            throw new Error(result.msg || '登录失败');
        } catch (error) {
            console.error('登录错误:', error);  // 添加错误日志
            throw error;
        }
    },
    
    // 获取用户基本信息和会员信息
    async getUserProfile() {
        try {
            // 并行请求用户信息和会员信息
            const [userInfo, membershipInfo] = await Promise.all([
                this.request('/api/auth/me'),
                this.request('/api/memberships/me')
            ]);
            
            // 存储到全局状态
            if (userInfo) {
                AppState.setUserInfo(userInfo);
            }
            if (membershipInfo) {
                AppState.setMembershipInfo(membershipInfo);
            }
            
            return {
                userInfo,
                membershipInfo
            };
        } catch (error) {
            console.error('获取用户资料失败:', error);
            // 即使获取会员信息失败，也返回用户基本信息
            return {
                userInfo: await this.request('/api/auth/me'),
                membershipInfo: null
            };
        }
    },

    // 获取会员套餐信息
    async getMembershipInfo() {
        try {
            const data = await this.request('/api/memberships/me');
            if (data) {
                AppState.setMembershipInfo(data);
            }
            return data;
        } catch (error) {
            console.error('获取会员信息失败:', error);
            return null;
        }
    },
    
    // 修改 loadInitialData 方法
    async loadInitialData() {
        try {
            // 获取完整的用户资料
            const profileData = await this.getUserProfile();
            return profileData;
        } catch (error) {
            console.error('加载初始数据失败:', error);
            throw error;
        }
    },

    // 激活卡密
    async activateCDKey(code) {
        return await this.request('/api/cdkeys/redeem', {
            method: 'POST',
            body: JSON.stringify({ code })
        });
    },

    // 查询卡密状态
    async checkCDKey(code) {
        return await this.request(`/api/cdkeys/check/${code}`);
    },

    // 为了向后兼容，保留 getUserInfo 方法
    async getUserInfo() {
        const { userInfo } = await this.getUserProfile();
        return userInfo;
    },

    // 获取套餐列表
    async getMembershipPlans(page = 1, pageSize = 10) {
        return await this.request(`/api/memberships/plans?page=${page}&page_size=${pageSize}`);
    }
};

async function handleLoginSuccess(result) {
    localStorage.setItem('access_token', result.data.token);
    showMessage('登录成功', 'success');
    
    // 触发登录成功事件
    const loginSuccessEvent = new Event('loginSuccess');
    document.dispatchEvent(loginSuccessEvent);
    
    // 延迟跳转到主页
    setTimeout(() => {
        window.location.href = '/';
    }, 1000);
} 